<?php
	global $_W,$_GPC;
	load() -> func('tpl');
	$ops = array('display', 'edit', 'delete','detail'); // 只支持此 3 种操作.
	$op = in_array($_GPC['op'], $ops) ? $_GPC['op'] : 'display';

	if($op == 'display'){
		$pindex = max(1, intval($_GPC['page']));
		$psize = 10;
		$orderId = trim($_GPC['orderId']);
		$info = trim($_GPC['info']);
		$time = $_GPC['time'];
		$condition = '';
		if (empty($starttime) || empty($endtime)) {
			$starttime = strtotime('-1 month');
			$endtime = time();
		}
		if (!empty($_GPC['time'])) {
			$starttime = strtotime($_GPC['time']['start']);
			$endtime = strtotime($_GPC['time']['end']) ;
			$condition .= " AND  createdAt >= '{$starttime}' AND  createdAt <= '{$endtime}'";
		}
		if ($orderId!='') {
			$condition .= " AND  orderId LIKE '%{$_GPC['orderId']}%'";
		}
		if ($info!='') {
			$condition .= " AND name LIKE '%{$info}%' or sender LIKE '%{$info}%' or receiver LIKE '%{$info}%' or smobile LIKE '%{$info}%' or rmobile LIKE '%{$info}%'";
		}


		$orders = pdo_fetchall("select * from".tablename('ew_delivery_order')."where uniacid={$_W['uniacid']}  $condition order by createdAt desc " . "LIMIT " . ($pindex - 1) * $psize . ',' . $psize);

		$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('ew_delivery_order') . " WHERE uniacid = '{$_W['uniacid']}'  $condition");
		$pager = pagination($total, $pindex, $psize);

		include $this->template('order_display');
	}
	//运单编辑
	if ($op == 'edit') {
		$id = intval($_GPC['id']);
		if(!empty($id)){
			$order = m('order')->getOrdersById($id);
			if(empty($order)){
				message('未找到指定的运单.', $this->createWebUrl('order') , 'error');
			}
		}

		if (checksubmit()) {
			$data = $_GPC['order'];
			if(empty($order)){
				$order = m('order')->getOrdersByOrderId($data['orderId']);
				if($order){
					message('运单号已经存在.', $this->createWebUrl('order', array('op' => 'edit')) , 'error');
				}
				$data['uniacid'] = $_W['uniacid'];
				$data['createdAt'] = TIMESTAMP;
				$data['updatedAt'] = TIMESTAMP;
				$ret = pdo_insert('ew_delivery_order', $data);
			} else {
				$data['updatedAt'] = TIMESTAMP;
				$ret = pdo_update('ew_delivery_order', $data, array('id'=>$id));
			}

			message('运单信息保存成功', $this->createWebUrl('order'), 'success');
		}

		include $this->template('order_edit');
	}

	if($op == 'delete') {
		$id = intval($_GPC['id']);

		if(empty($id)){
			message('未找到指定运单');
		}
	
		$order = m('order')->getOrdersById($id);
		$result = pdo_delete('ew_delivery_order_detail', array('orderid'=>$order['orderId'], 'uniacid'=>$_W['uniacid']));
                $result = pdo_delete('ew_delivery_order', array('id'=>$id, 'uniacid'=>$_W['uniacid']));
                if($result){
			echo json_encode(array('status' => 1 , 'msg' => '删除成功'));
		} else {
			echo json_encode(array('status' => 0 , 'msg' => '删除失败'));
		}
	}
?>
